Page({
  data: {
    // 菜谱基本信息
    recipeName: "",
    
    // 用料相关
    materialRows: [
      {
        materialName: "",
        materialUnit: ""
      }
    ],
    materialTags: [],
    
    // 步骤相关
    steps: [
      {
        description: "",
        imagePath: ""
      }
    ],
    
    // 烹饪时长
    cookTimeId: null, 
    cookTimeList: [],
    
    // 烹饪难度
    difficultyId: null, 
    cookLevelList: [],
    
    // 封面图路径
    coverPath: "",
    
    // 选中的分类（单选，只能选择一个）
    selectedCategory: null,
    
    // 分类数据（用于显示分类名称）
    categoryList: [
      { name: "烤箱", value: 1 },
      { name: "蒸", value: 2 },
      { name: "披萨", value: 3 },
      { name: "创意菜", value: 4 },
      { name: "快手菜", value: 5 },
      { name: "电饭煲", value: 6 },
      { name: "甜品", value: 7 }
    ]
  },

  onLoad() {
    // 页面加载时，监听其他页面返回的数据
    const that = this;
    wx.onAppRoute(function(res) {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      // 判断当前页面是否是当前页面
      if (currentPage.route === "pages/recipe/recipe") {
        // 检查是否有传递过来的图片
        if (currentPage.options.imageUrl) {
          that.setData({
            coverPath: decodeURIComponent(currentPage.options.imageUrl)
          });
        }
      }
    });

    // 获取烹饪时长选项
    this.getCookTimeOptions();
    
    // 获取烹饪难度选项
    this.getDifficultyOptions();
  },

  // 选择封面图
  chooseCover() {
    wx.showActionSheet({
      itemList: ["拍照", "从相册选择"],
      itemColor: "#333",
      success: (res) => {
        if (res.tapIndex === 0) {
          // 拍照
          this._chooseImage("cover", "camera"); 
        } else if (res.tapIndex === 1) {
          // 从相册选择
          this._chooseImage("cover", "album");
        }
      },
      fail: (err) => {
        console.log("选择菜单失败: ", err);
      }
    });
  },

  /**
   * 删除封面图
   */
  deleteCover() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张封面图吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            coverPath: ""
          });
          wx.showToast({
            title: '已删除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 删除封面图
  deleteCover() {
    wx.showModal({
      title: '提示',
      content: '确定要删除这张封面图吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            coverPath: ""
          });
        }
      }
    });
  },

  // 步骤图选择
  chooseStepImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.showActionSheet({
      itemList: ["拍照", "从相册选择"],
      itemColor: "#333",
      success: (res) => {
        if (res.tapIndex === 0) {
          // 拍照
          this._chooseImage("step", "camera", index);
        } else if (res.tapIndex === 1) {
          wx.navigateTo({
            url: `/transmit/pages/transmitphoto/transmitphoto?type=step&index=${index}`,
            success: () => {
              console.log("跳转成功");
            },
            fail: (err) => {
              console.log("跳转失败: ", err);
            }
          });
        }
      },
      fail: (err) => {
        console.log("选择菜单失败: ", err);
      }
    });
  },

  // 删除步骤图
  deleteStepImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '提示',
      content: '确定要删除这张步骤图吗？',
      success: (res) => {
        if (res.confirm) {
          const steps = [...this.data.steps];
          steps[index].imagePath = "";
          this.setData({ steps });
        }
      }
    });
  },

  // 通用方法：调用系统选择图片
  _chooseImage(type, sourceType, index) {
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: [sourceType],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        console.log(`选择的${type}图片路径:`, tempFilePath);
        
        // 显示上传中提示
        wx.showLoading({ title: '正在上传...' });
        
        // 调用封装的图片上传方法
        this.uploadImage(tempFilePath, type, index);
      },
      fail: (err) => {
        console.log(`选择${type}图失败：`, err);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 封装的图片上传方法
   * @param {string} filePath - 图片文件路径
   * @param {string} type - 图片类型（'cover' 或 'step'）
   * @param {number} index - 步骤索引（仅步骤图需要）
   */
  uploadImage(filePath, type, index) {
    // 构建上传请求配置
    const uploadConfig = {
      url: 'http://localhost:8080/common/upload',
      filePath: filePath,
      name: 'file',
      formData: {
        // 可以添加其他表单数据
      },
      success: (res) => {
        console.log(`${type}图片上传成功:`, res);
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          try {
            const data = JSON.parse(res.data);
            console.log('解析后的响应数据:', data);
            
            if (data.code === 200) {
              // 获取图片URL，优先使用 url 字段，其次使用 data 字段
              const imageUrl = data.url || data.data || data.fileName;
              console.log(`设置的${type}图片URL:`, imageUrl);
              
              // 根据类型设置不同的数据字段
              if (type === "cover") {
                this.setData({
                  coverPath: imageUrl
                });
              } else if (type === "step" && index !== undefined) {
                const steps = [...this.data.steps];
                steps[index].imagePath = imageUrl;
                this.setData({ steps });
              }
              
              wx.showToast({
                title: '上传成功',
                icon: 'success'
              });
            } else {
              console.error('服务器返回错误:', data);
              wx.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              });
            }
          } catch (parseError) {
            console.error('解析响应数据失败:', parseError);
            wx.showToast({
              title: '响应数据格式错误',
              icon: 'none'
            });
          }
        } else {
          console.error('HTTP状态码错误:', res.statusCode);
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error(`${type}图片上传失败:`, err);
        wx.hideLoading();
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    };
    
    // 执行上传
    wx.uploadFile(uploadConfig);
  },

  // 输入框事件
  onRecipeNameInput(e) {
    this.setData({ recipeName: e.detail.value });
  },

  onMaterialNameInput(e) {
    const index = e.currentTarget.dataset.index;
    const materialRows = [...this.data.materialRows];
    materialRows[index].materialName = e.detail.value;
    this.setData({ materialRows });
  },

  onMaterialUnitInput(e) {
    const index = e.currentTarget.dataset.index;
    const materialRows = [...this.data.materialRows];
    materialRows[index].materialUnit = e.detail.value;
    this.setData({ materialRows });
  },

  onStepDescInput(e) {
    const index = e.currentTarget.dataset.index;
    const steps = [...this.data.steps];
    steps[index].description = e.detail.value;
    this.setData({ steps });
  },

  // 用料操作
  removeTag(e) {
    const index = e.currentTarget.dataset.index;
    const newTags = this.data.materialTags.filter((_, i) => i !== index);
    this.setData({ materialTags: newTags });
  },

  addMaterialRow() {
    const materialRows = [...this.data.materialRows];
    materialRows.push({
      materialName: "",
      materialUnit: ""
    });
    this.setData({ materialRows });
    wx.showToast({
      title: "已新增一行",
      icon: "none"
    });
  },

  // 步骤操作
  addStep() {
    const steps = [...this.data.steps];
    steps.push({
      description: "",
      imagePath: ""
    });
    this.setData({ steps });
  },

  /**
   * 选择步骤图片
   * @param {Object} e - 点击事件
   */
  chooseStepImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.showActionSheet({
      itemList: ["拍照", "从相册选择"],
      itemColor: "#333",
      success: (res) => {
        if (res.tapIndex === 0) {
          // 拍照
          this._chooseImage("step", "camera", index);
        } else if (res.tapIndex === 1) {
          // 从相册选择
          this._chooseImage("step", "album", index);
        }
      },
      fail: (err) => {
        console.log("选择菜单失败:", err);
      }
    });
  },

  removeStep(e) {
    const index = e.currentTarget.dataset.index;
    const steps = this.data.steps.filter((_, i) => i !== index);
    this.setData({ steps });
  },

  // 烹饪时长和难度选择
  onCookTimeChange(e) {
    this.setData({ cookTimeId: e.currentTarget.dataset.value });
  },

  onCookLevelChange(e) {
    this.setData({ difficultyId: e.currentTarget.dataset.value });
  },

  // 跳转到分类选择
  goToCategory() {
    wx.navigateTo({
      url: "/transmit/pages/transmitselect/transmitselect"
    });
  },

  // 根据分类值获取分类名称
  getCategoryName(value) {
    const category = this.data.categoryList.find(item => item.value === value);
    return category ? category.name : '未知分类';
  },

  // 获取烹饪时长选项
  getCookTimeOptions() {
    const { get } = require('../../../utils/request.js');
    
    get('/collect/recipes/cook-time-options')
      .then(res => {
        console.log('烹饪时长选项:', res);
        if (res && res.data) {
          this.setData({
            cookTimeList: res.data
          });
          // 设置默认选中第一个选项
          if (res.data.length > 0) {
            this.setData({
              cookTimeId: res.data[0].id
            });
          }
        }
      })
      .catch(err => {
        console.error('获取烹饪时长选项失败:', err);
        // 设置默认选项
        this.setDefaultCookTimeOptions();
      });
  },

  // 获取烹饪难度选项
  getDifficultyOptions() {
    const { get } = require('../../../utils/request.js');
    
    get('/collect/recipes/difficulty-options')
      .then(res => {
        console.log('烹饪难度选项:', res);
        if (res && res.data) {
          this.setData({
            cookLevelList: res.data
          });
          // 设置默认选中第一个选项
          if (res.data.length > 0) {
            this.setData({
              difficultyId: res.data[0].id
            });
          }
        }
      })
      .catch(err => {
        console.error('获取烹饪难度选项失败:', err);
        // 设置默认选项
        this.setDefaultDifficultyOptions();
      });
  },

  // 设置默认烹饪时长选项（接口失败时的备用方案）
  setDefaultCookTimeOptions() {
    const defaultOptions = [];
    this.setData({
      cookTimeList: defaultOptions,
      cookTimeId: 1
    });
  },

  // 设置默认烹饪难度选项（接口失败时的备用方案）
  setDefaultDifficultyOptions() {
    const defaultOptions = [
      { id: 1, text: "零厨艺" },
      { id: 2, text: "容易做" },
      { id: 3, text: "有点挑战" },
      { id: 4, text: "非常难" }
    ];
    this.setData({
      cookLevelList: defaultOptions,
      difficultyId: 1
    });
  },

  // 发布菜谱
  publishRecipe() {
    // 简单校验
    if (!this.data.recipeName.trim()) {
      wx.showToast({ 
        title: "请填写菜谱名称", 
        icon: "none" 
      });
      return;
    }
    
    if (!this.data.coverPath) {
      wx.showToast({ 
        title: "请添加菜谱封面", 
        icon: "none" 
      });
      return;
    }
    
    if (this.data.steps.length === 0 || !this.data.steps[0].description.trim()) {
      wx.showToast({ 
        title: "请填写至少一个步骤说明", 
        icon: "none" 
      });
      return;
    }

    // 引入网络请求工具和API配置
    const { post } = require('../../../utils/request.js');
    const { RECIPE_API } = require('../../../utils/api.js');
    
    // 准备发送的数据
    const recipeData = {
      title: this.data.recipeName,
      materialRows: this.data.materialRows,
      materialTags: this.data.materialTags,
      steps: this.data.steps,
      cookTimeId: this.data.cookTimeId,
      difficultyId: this.data.difficultyId,
      coverUrl: this.data.coverPath,
      categoryId: this.data.selectedCategory
    };

    console.log("准备发送的菜谱数据:", recipeData);
    
    // 发送POST请求到服务器
    post(RECIPE_API.PUBLISH, recipeData)
      .then(res => {
        console.log("发布成功，服务器响应:", res);
        
        wx.showToast({ 
          title: "发布成功", 
          icon: "success",
          duration: 2000
        });
        
        // 发布成功后重置表单
        setTimeout(() => {
          this.setData({
            recipeName: "",
            materialRows: [
              {
                materialName: "",
                materialUnit: ""
              }
            ],
            materialTags: [],
            steps: [
              {
                description: "",
                imagePath: ""
              }
            ],
            coverPath: "",
            cookTimeId: this.data.cookTimeList.length > 0 ? this.data.cookTimeList[0].id : null,
            difficultyId: this.data.cookLevelList.length > 0 ? this.data.cookLevelList[0].id : null,
            selectedCategory: null
          });
        }, 2000);
      })
      .catch(err => {
        console.error('发布失败:', err);
        
        wx.showToast({ 
          title: "发布失败，请重试", 
          icon: "none",
          duration: 2000
        });
      });
  }
});
